package com.hopelic.canal.database.sync;

import cn.cz.common.canal.sync.handle.CanalDTO;
import cn.cz.common.canal.sync.handle.EventTypeEnum;
import cn.cz.common.canal.sync.handle.ICanalSchemaHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
@Component
public class DefaultCanalSchemaHandler implements ICanalSchemaHandler {



    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public boolean isSupport(EventTypeEnum eventTypeEnum, String schemaName, String tableName) {
        return true;
    }

    @Override
    public void handlerDdl(CanalDTO canalDTO) {
        jdbcTemplate.execute(new ConnectionCallback<Boolean>() {
            @Override
            public Boolean doInConnection(Connection con) throws SQLException, DataAccessException {
                final Statement statement = con.createStatement();
                if (canalDTO.getEventTypeEnum()!=EventTypeEnum.QUERY&&StringUtils.hasText(canalDTO.getDdlSchemaName())) {
                    statement.addBatch(String.format("use %s", canalDTO.getDdlSchemaName()));
                }
                statement.addBatch(canalDTO.getDdlSql());
                statement.executeBatch();
                statement.clearBatch();
                return null;
            }
        });
    }
}
